using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class SwitchHelper : CompareHelper
    {
        public AudioClip clip;
        public SoundType soundType;
        public NodeHelper[] list;
        public GameObject on;
        public GameObject off;
        public bool click;
        public bool isDisabled;
        public bool isToggle;
        public bool isButton;
        private bool _b;
        private Button _Button;
        private Image _Image;
        private Toggle _Toggle;
        private bool show;

        private Toggle Toggle
        {
            get
            {
                if (_Toggle == null) _Toggle = GetComponent<Toggle>();

                return _Toggle;
            }
        }

        private Button Button
        {
            get
            {
                if (_Button == null) _Button = UnityTools.GetComponentRequire<Button>(gameObject);

                return _Button;
            }
        }

        private Image Image
        {
            get
            {
                if (_Image == null) _Image = GetComponent<Image>();
                return _Image;
            }
        }

        protected override void Start()
        {
            if (isDisabled) return;
            if (isToggle)
                Toggle.onValueChanged.AddListener(Switch);
            else if (isButton) UnityTools.GetComponentRequire<Button>(gameObject).onClick.AddListener(Switch);
        }

        public void Switch(bool b)
        {
            Switch();
        }

        public void Switch()
        {
            if (click)
                Click();
            else if (withKey && key != "")
                Change(key);
            else if (judgeValue != "")
                Change(judgeValue);
            else
                Change(!show);

            if (soundType != SoundType.None)
                Game.single.PlayEFF(soundType);
            else if (clip != null) Game.single.PlayEFF(clip);
        }

        public override void Show()
        {
            if (debug) LogTools.Log("{0} Show", gameObject.name);
            SetChildData(_data);
            show = true;
            for (var i = 0; i < list.Length; i++) list[i].SetData(true);
            if (on != null) on.SetActive(true);
            if (off != null) off.SetActive(false);
        }

        public override void Hide()
        {
            if (debug) LogTools.Log("{0} Hide", gameObject.name);
            SetChildData(_data);
            show = false;
            for (var i = 0; i < list.Length; i++) list[i].SetData(false);
            if (on != null) on.SetActive(false);
            if (off != null) off.SetActive(true);
        }
    }
}